package com.x.attendance.assemble.control.schedule;

import java.util.Date;
import java.util.List;

import com.x.attendance.assemble.control.service.AttendanceDataService;
import com.x.attendance.assemble.control.service.O2OAIntegrationService;
import com.x.attendance.core.entity.AttendanceDevice;
import com.x.attendance.core.entity.AttendanceRecord;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.schedule.AbstractJob;

/**
 * 考勤数据定时同步任务
 * @author Manus AI
 */
public class AttendanceSyncJob extends AbstractJob {

	private static Logger logger = LoggerFactory.getLogger(AttendanceSyncJob.class);
	
	private AttendanceDataService attendanceDataService;
	private O2OAIntegrationService o2oaIntegrationService;

	public AttendanceSyncJob() {
		this.attendanceDataService = new AttendanceDataService();
		this.o2oaIntegrationService = new O2OAIntegrationService();
	}

	@Override
	public void schedule() throws Exception {
		logger.info("开始执行考勤数据定时同步任务");
		
		try {
			// 1. 从设备采集考勤数据
			syncAttendanceDataFromDevices();
			
			// 2. 推送考勤数据到O2OA
			pushPendingRecordsToO2OA();
			
			// 3. 同步O2OA人员信息
			syncPersonInfoFromO2OA();
			
			logger.info("考勤数据定时同步任务执行完成");
			
		} catch (Exception e) {
			logger.error("考勤数据定时同步任务执行失败", e);
			throw e;
		}
	}

	/**
	 * 从设备同步考勤数据
	 */
	private void syncAttendanceDataFromDevices() {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			// 获取所有启用的设备
			List<AttendanceDevice> devices = emc.listEqual(AttendanceDevice.class, 
				AttendanceDevice.enabled_FIELDNAME, true);
			
			logger.info("开始从设备同步考勤数据: 设备数量={}", devices.size());
			
			int totalSynced = 0;
			
			for (AttendanceDevice device : devices) {
				try {
					// 检查设备状态
					if (!"ONLINE".equals(device.getStatus())) {
						logger.warn("设备不在线，跳过同步: {}", device.getName());
						continue;
					}
					
					// 从设备采集考勤记录
					List<AttendanceRecord> records = attendanceDataService.collectRecordsFromDevice(device);
					
					if (records != null && !records.isEmpty()) {
						// 保存考勤记录
						emc.beginTransaction(AttendanceRecord.class);
						
						for (AttendanceRecord record : records) {
							// 验证记录数据
							if (attendanceDataService.validateAttendanceRecord(record)) {
								record.setSyncStatus("PENDING");
								record.setSyncTime(new Date());
								emc.persist(record);
								totalSynced++;
							}
						}
						
						emc.commit();
						
						// 更新设备最后同步时间
						emc.beginTransaction(AttendanceDevice.class);
						device.setLastSyncTime(new Date());
						emc.check(device, AttendanceDevice.class);
						emc.commit();
						
						logger.info("设备考勤数据同步成功: 设备={}, 记录数={}", device.getName(), records.size());
					}
					
				} catch (Exception e) {
					logger.error("设备考勤数据同步失败: 设备=" + device.getName(), e);
					
					// 更新设备状态为错误
					try {
						emc.beginTransaction(AttendanceDevice.class);
						device.setStatus("ERROR");
						emc.check(device, AttendanceDevice.class);
						emc.commit();
					} catch (Exception ex) {
						logger.error("更新设备状态失败", ex);
					}
				}
			}
			
			logger.info("设备考勤数据同步完成: 总同步记录数={}", totalSynced);
			
		} catch (Exception e) {
			logger.error("从设备同步考勤数据失败", e);
		}
	}

	/**
	 * 推送待同步记录到O2OA
	 */
	private void pushPendingRecordsToO2OA() {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			// 获取待同步的考勤记录
			List<AttendanceRecord> pendingRecords = emc.listEqual(AttendanceRecord.class, 
				AttendanceRecord.syncStatus_FIELDNAME, "PENDING");
			
			if (pendingRecords.isEmpty()) {
				logger.info("没有待同步的考勤记录");
				return;
			}
			
			logger.info("开始推送考勤数据到O2OA: 记录数量={}", pendingRecords.size());
			
			// 分批推送，避免一次性推送过多数据
			int batchSize = 100;
			for (int i = 0; i < pendingRecords.size(); i += batchSize) {
				int endIndex = Math.min(i + batchSize, pendingRecords.size());
				List<AttendanceRecord> batch = pendingRecords.subList(i, endIndex);
				
				try {
					o2oaIntegrationService.pushAttendanceToO2OA(batch);
					logger.info("批次推送完成: {}/{}", endIndex, pendingRecords.size());
				} catch (Exception e) {
					logger.error("批次推送失败: " + (i + 1) + "-" + endIndex, e);
				}
			}
			
			logger.info("考勤数据推送到O2OA完成");
			
		} catch (Exception e) {
			logger.error("推送考勤数据到O2OA失败", e);
		}
	}

	/**
	 * 同步O2OA人员信息
	 */
	private void syncPersonInfoFromO2OA() {
		try {
			logger.info("开始同步O2OA人员信息");
			o2oaIntegrationService.syncPersonFromO2OA();
			logger.info("O2OA人员信息同步完成");
		} catch (Exception e) {
			logger.error("同步O2OA人员信息失败", e);
		}
	}

	/**
	 * 清理过期的考勤记录
	 */
	private void cleanupExpiredRecords() {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			// 删除3个月前的已同步记录
			Date threeMonthsAgo = new Date(System.currentTimeMillis() - (90L * 24 * 60 * 60 * 1000));
			
			// 这里应该实现清理逻辑
			// 由于O2OA的EntityManager可能不支持批量删除，需要逐条删除
			
			logger.info("考勤记录清理完成");
			
		} catch (Exception e) {
			logger.error("清理过期考勤记录失败", e);
		}
	}
}

